<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/7/23
 * Time: 13:37
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Goods extends Base
{
    /**
     * 消息首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'good_status' => ['<>',3]
            ];
            //状态
            if(isset($params['n_range']) && $params['n_range'] != ''){
                if($params['n_range'] == 3){
                    $where['good_status'] = 1;
                    $where['good_stock'] = ['<=',0];
                }else{
                    $where['good_status'] = $params['n_range'];
                }

            }
            // 名字
            if(isset($params['n_title']) && $params['n_title'] != ''){
                $where['good_name|school_name|good_coding'] = ['like', '%' . $params['n_title'] . '%'];
            }
            $field=input('field');//字段
            $order=input('order');//排序方式
            if($field && $order){
                $od="g.".$field." ".$order;
            }else{
                $od="good_status asc,good_sort asc,good_update_time desc";
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'g.*,school_name,school_id';
            $count = Db::table('up_self_goods')->alias('g')
                ->join('up_school s','g.good_school=s.school_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_self_goods')->alias('g')
                ->join('up_school s','g.good_school=s.school_id','LEFT')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order($od)
                ->field($field)
                ->select();
            foreach ($lists as $k => $v){
                $new = Db::table('up_self_goods_attr')
                    ->where('is_delete',0)
                    ->where('goods_id',$v['good_id'])
                    ->sum('stock');
                $lists[$k]['good_stock'] = $new;
                if($new != $v['good_stock']) Db::table('up_self_goods')->where('good_id',$v['good_id'])->setField('good_stock',$new);
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 改状态
     * @author
     */
    public function changeGoodStatus()
    {
        extract(input());
        $res = Db::table('up_self_goods')
            ->where('good_id',$id)
            ->update([
                'good_update_time' => date('Y-m-d H:i:s'),
                'good_status' => $num
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }

    /**
     * 排序编辑
     * @return mixed|\think\response\Json
     */
    public function updateSort(){
        $id = input('id');
        $param = [
            'good_sort'=>input('value'),
        ];
        $res = Db::name('self_goods')->where('good_id',$id)->update($param);
        if($res){
            return json(['code' => 200, 'msg' => '修改成功']);
        }else{
            return json(['code' => 100, 'msg' =>' 修改失败']);
        }
    }


    /**
     * 发布商品
     * @return mixed|\think\response\Json
     */
    public function goodAdd(){
        if(Request::instance()->isPost()){
            Db::startTrans();
            try{
                $params = input('param.');
                $time = date('Y-m-d H:i:s');
                $gg_json = json_decode($params['gg_json'],true);
                $data = [
                    'good_name' => trim($params['good_name'], ' '), // 标题
                    'good_price' => round($params['good_price'], 2),// 内容
                    'good_thumb' => $params['good_thumb'],// 内容
                    'good_coding' => trim($params['good_coding'],' '),// 内容
                    'good_image' => $params['good_image'],// 内容
                    'good_status' => $params['good_status'],// 内容
                    'good_stock' => 0,// 内容
                    'good_content' => $params['content'],// 内容
                    'good_school' => $params['good_school'],// 内容
                    'good_guige' => json_encode($gg_json),// 内容
                    'good_create_time' => $time, // 推送时间
                    'good_update_time' => $time, // 推送时间
                ];
                $goods_id = Db::table('up_self_goods')->insertGetId($data);
                //先添加商品
                $bodyData = [
                    'goods_sn' => substr($data['good_coding'],0,13),
                    'goods_name' => $data['good_name'],
                    'goods_id' => $goods_id,
                    'market_price' => $data['good_price'],
                    'bzsj' => $data['good_price'],
                    'sp' => 1,
                    'sprq' => date('Y-m-d'),
                    'is_combo' => 0,
                    'goodscj' => 0,
                    'enable' => $data['good_status']
                ];
                $addres = $this->goodsAddOms('products.add',json_encode($bodyData));
                if($addres['status'] != 'api-success'){
                    Db::rollback();
                    return json(['code' => 100, 'msg' => '同步oms失败~']);
                }
                //attrs
                $attrs = trim($params['attr_json'],'|||');
                $attr_arr = explode('|||',$attrs);
                $rightStore = 0;
                foreach ($attr_arr as $k=>$v){
                    $v_arr = explode('___',$v);
                    $attr_insert = [
                        'goods_id' => $goods_id,
                        'sign_str' => $v_arr[0],
                        'sign_id' => $v_arr[1],
                        'price' => round($v_arr[2],2),
                        'stock' => (int)$v_arr[3],
                        'no' => $v_arr[4],
                        'weight' => $v_arr[5],
                        'pic_url' => $v_arr[6],
                    ];
                    Db::table('up_self_goods_attr')->insert($attr_insert);
                    $rightStore += (int)$v_arr[3];
                    //再添加商品的sku
                    $bodyData = [
                        'goods_sn' => substr($data['good_coding'],0,13),
                        'color_code' => '2022',
                        'size_code' => $v_arr[0]
                    ];
                    $bodyData['sku'] = $bodyData['goods_sn'] . $bodyData['size_code'];
                    $addres = $this->goodsAddOms('skus.add',json_encode($bodyData));
                    if($addres['status'] != 'api-success'){
                        Db::rollback();
                        return json(['code' => 100, 'msg' => '同步sku失败~']);
                    }
                }
                if($rightStore > 0){
                    Db::table('up_self_goods')->where('good_id',$goods_id)->setField('good_stock',$rightStore);
                }
                Db::commit();
                return json(['code' => 200, 'msg' => '发布成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '发布失败']);
            }
        }
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->select();
        $this->assign([
            'school' => $school
        ]);
        return $this->fetch('goods/goodadd');
    }
    /**
     * 编辑商品
     * @return mixed|\think\response\Json
     */
    public function goodEdit(){
        if(Request::instance()->isPost()){
            Db::startTrans();
            try{
                $params = input('param.');
                $time = date('Y-m-d H:i:s');
                $gg_json = json_decode($params['gg_json'],true);
                $data = [
                    'good_name' => trim($params['good_name'], ' '), // 标题
                    'good_price' => round($params['good_price'], 2),// 内容
                    'good_thumb' => $params['good_thumb'],// 内容
                    'good_coding' => $params['good_coding'],// 内容
                    'good_image' => $params['good_image'],// 内容
                    'good_status' => $params['good_status'],// 内容
                    'good_stock' => 0,// 内容
                    'good_content' => $params['content'],// 内容
                    'good_school' => $params['good_school'],// 内容
                    'good_guige' => json_encode($gg_json),// 内容
                    'good_update_time' => $time, // 推送时间
                ];
                $goods_id = $params['good_id'];
                $havechange = $params['havechange'];
                $oldCoding = Db::table('up_self_goods')->where('good_id',$goods_id)->value('good_coding');
                Db::table('up_self_goods')->where('good_id',$goods_id)->update($data);
                $rightStore = 0;
                //先添加商品
                $newCoding = substr($data['good_coding'],0,13);
                if($newCoding != $oldCoding){
                    $bodyData = [
                        'goods_sn' => $newCoding,
                        'goods_name' => $data['good_name'],
                        'goods_id' => $goods_id,
                        'market_price' => $data['good_price'],
                        'bzsj' => $data['good_price'],
                        'sp' => 1,
                        'sprq' => date('Y-m-d'),
                        'is_combo' => 0,
                        'goodscj' => 0,
                        'enable' => $data['good_status']
                    ];
                    $addres = $this->goodsAddOms('products.add',json_encode($bodyData));
                    if($addres['status'] != 'api-success'){
                        Db::rollback();
                        return json(['code' => 100, 'msg' => '同步oms失败~']);
                    }
                }
                //attrs
                $attrs = trim($params['attr_json'],'|||');
                $attr_arr = explode('|||',$attrs);
                if($havechange == 1){
                    foreach ($attr_arr as $k=>$v){
                        $v_arr = explode('___',$v);
                        $attr_insert = [
                            'goods_id' => $goods_id,
                            'sign_str' => $v_arr[0],
                            'sign_id' => $v_arr[1],
                            'price' => round($v_arr[2],2),
                            'stock' => (int)$v_arr[3],
                            'no' => $v_arr[4],
                            'weight' => $v_arr[5],
                            'pic_url' => $v_arr[6],
                        ];
                        Db::table('up_self_goods_attr')
                            ->where('goods_id',$goods_id)
                            ->where('sign_id',$v_arr[1])
                            ->where('is_delete',0)
                            ->update($attr_insert);
                        $rightStore += (int)$v_arr[3];
                        //再添加商品的sku
                        if($oldCoding != $newCoding){
                            $bodyData = [
                                'goods_sn' => $newCoding,
                                'color_code' => '2022',
                                'size_code' => $v_arr[0]
                            ];
                            $bodyData['sku'] = $newCoding . $bodyData['size_code'];
                            $addres = $this->goodsAddOms('skus.add',json_encode($bodyData));
                            if($addres['status'] != 'api-success'){
                                Db::rollback();
                                return json(['code' => 100, 'msg' => '同步sku失败~']);
                            }
                        }
                    }
                }else{
                    Db::table('up_self_goods_attr')
                        ->where('goods_id',$goods_id)
                        ->setField('is_delete',1);
                    foreach ($attr_arr as $k=>$v){
                        $v_arr = explode('___',$v);
                        $attr_insert = [
                            'goods_id' => $goods_id,
                            'sign_str' => $v_arr[0],
                            'sign_id' => $v_arr[1],
                            'price' => round($v_arr[2],2),
                            'stock' => (int)$v_arr[3],
                            'no' => $v_arr[4],
                            'weight' => $v_arr[5],
                            'pic_url' => $v_arr[6],
                        ];
                        Db::table('up_self_goods_attr')->insert($attr_insert);
                        $rightStore += (int)$v_arr[3];
                        //再添加商品的sku
                        if($oldCoding != $newCoding){
                            $bodyData = [
                                'goods_sn' => $newCoding,
                                'color_code' => '2022',
                                'size_code' => $v_arr[0]
                            ];
                            $bodyData['sku'] = $newCoding . $bodyData['size_code'];
                            $addres = $this->goodsAddOms('skus.add',json_encode($bodyData));
                            if($addres['status'] != 'api-success'){
                                Db::rollback();
                                return json(['code' => 100, 'msg' => '同步sku失败~']);
                            }
                        }
                    }
                }
                if($rightStore > 0){
                    Db::table('up_self_goods')->where('good_id',$goods_id)->setField('good_stock',$rightStore);
                }
                Db::commit();
                return json(['code' => 200, 'msg' => '更新成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '更新失败']);
            }
        }
        $g_id = input('good_id');
        $data = Db::table('up_self_goods')
            ->where('good_id',$g_id)
            ->find();
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->select();
        $guige = json_decode($data['good_guige'],true);
        $atrrs = Db::table('up_self_goods_attr')
            ->where('goods_id',$g_id)
            ->where('is_delete',0)
            ->select();
        $temp_key = array_column($atrrs,'sign_id');
        $attr_arr = array_combine($temp_key,$atrrs) ;
        $this->assign([
            'school' => $school,
            'data' => $data,
            'guige' => $guige,
            'atrrs' => json_encode($attr_arr)
        ]);
        return $this->fetch('goods/goodedit');
    }
    
    /**
     * 商品详情
     * @return mixed
     */
    public function goodInfo(){
        $g_id = input('good_id');
        $data = Db::table('up_self_goods')
            ->where('good_id',$g_id)
            ->find();
        //所有学校
        $school = Db::table('up_school')
            ->field('school_id, school_name')
            ->select();
        $guige = json_decode($data['good_guige'],true);
        $atrrs = Db::table('up_self_goods_attr')
            ->where('goods_id',$g_id)
            ->where('is_delete',0)
            ->select();
        $temp_key = array_column($atrrs,'sign_id');
        $attr_arr = array_combine($temp_key,$atrrs) ;
        $this->assign([
            'school' => $school,
            'data' => $data,
            'guige' => $guige,
            'atrrs' => json_encode($attr_arr)
        ]);
        return $this->fetch('goods/goodinfo');
    }
    

    /**
     * 删除商品
     * @return \think\response\Json
     */
    public function goodDel(){
        $g_id = input('id');
        $res = Db::table('up_self_goods')->where('good_id',$g_id)->setField('good_status',3);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * 查看评价
     * @return mixed|\think\response\Json
     */
    public function goodsComments(){
        if(request()->isAjax()){
            extract(input());
            $good_id = input('good_id');
            $where = [
                'comment_good_id' => $good_id
            ];
            $count = Db::name('self_goods_comment')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join('up_self_goods g','a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('self_goods_comment')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join('up_self_goods g','a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->field('a.*,uuu.user_username,uuu.user_phone,good_name')
                ->select();
            if($lists){
                foreach ($lists as $k=>$v){
                    if($v['comment_image']){
                        $lists[$k]['comment_image'] = explode(',',$v['comment_image']);
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $good_id = input('good_id');
        $this->assign('good_id',$good_id);
        return $this->fetch('goods/goodscomments');
    }
    //导出
    public function excelOutOrder()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        $params = input('param.');
        $where = [
            'good_status' => ['<>',3]
        ];
        //状态
        if(isset($params['n_range']) && $params['n_range'] != ''){
            if($params['n_range'] == 3){
                $where['good_status'] = 1;
                $where['good_stock'] = ['<=',0];
            }else{
                $where['good_status'] = $params['n_range'];
            }

        }
        // 名字
        if(isset($params['n_title']) && $params['n_title'] != ''){
            $where['good_name|school_name|good_coding'] = ['like', '%' . $params['n_title'] . '%'];
        }
        $field = [
            'good_name','good_coding','good_price','good_thumb','good_status','good_stock'
            ,'good_create_time','good_update_time'
        ];
        $data = Db::table('up_self_goods')->alias('g')
            ->join('up_school s','g.good_school=s.school_id','LEFT')
            ->where($where)
            ->field($field)
            ->order('good_status asc')
            ->select();
        if($data){
            $cellname = [
                '商品名字','商品编码','价格', '缩略图地址', '商品状态', '库存',
                '创建时间','最后更新时间'

            ];
            $status = ['good_status'];
            $values = [
                'good_status' => [1 => '正常',2 => '冻结']
            ];
            $res = exportExcel('GoodInfo',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    //导出
    public function excelOutDetail()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        $params = input('param.');
        $where = [
            'good_status' => ['<>',3],
            'is_delete' => 0
        ];
        //状态
        if(isset($params['n_range']) && $params['n_range'] != ''){
            if($params['n_range'] == 3){
                $where['good_status'] = 1;
                $where['good_stock'] = ['<=',0];
            }else{
                $where['good_status'] = $params['n_range'];
            }

        }
        // 名字
        if(isset($params['n_title']) && $params['n_title'] != ''){
            $where['good_name|school_name|good_coding'] = ['like', '%' . $params['n_title'] . '%'];
        }
        $field = [
            'good_name','good_coding','good_thumb','good_status','good_stock'
            ,'sign_str','stock','price','pic_url'
        ];
        $data = Db::table('up_self_goods_attr')->alias('a')
            ->join('up_self_goods g','a.goods_id=g.good_id','LEFT')
            ->join('up_school s','g.good_school=s.school_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '所属商品','商品编码', '商品缩略图地址', '商品状态', '总库存',
                '规格','规格库存','规格价格','规格图片地址'

            ];
            $status = ['good_status'];
            $values = [
                'good_status' => [1 => '正常',2 => '冻结']
            ];
            $res = exportExcel('GoodInfo',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}